package cn.virens.library.widget.form.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.virens.library.uitls.LogUtil;
import cn.virens.library.widget.form.Form;
import cn.virens.library.widget.form.FormTextLayoutInter;
import cn.virens.library.widget.form.FormTextViewInter;


/**
 * 表单 展示控件组
 * Created by virens on 2017/6/17.
 */
public class FormTextLayout extends LinearLayout implements FormTextLayoutInter {
    private Map<String, Object> valueMap;

    public FormTextLayout(Context context) {
        this(context, null);
    }

    public FormTextLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FormTextLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public Map<String, Object> getValue() {
        return valueMap;
    }

    @Override
    public void setValue(Map<String, Object> map) {
        this.valueMap = map;
        // 显示value
        if (map == null) return;
        // 获取全部展示控件
        List<Form> list = getFormControls(this);
        // 遍历依次设置值
        for (int i = 0; i < list.size(); i++) {
            Form view = list.get(i);

            if (view instanceof FormTextViewInter) {
                String name = ((FormTextViewInter) view).getName();
                Object value = map.get(name);

                ((FormTextViewInter) view).setValue(value);
            } else if (view instanceof FormTextLayoutInter) {
                ((FormTextLayoutInter) view).setValue(map);
            } else {
                LogUtil.d("非展示控件");
            }
        }
    }

    public List<Form> getFormControls(ViewGroup view) {
        List<Form> result = new ArrayList<>();

        for (int i = 0; i < view.getChildCount(); i++) {
            View child = view.getChildAt(i);

            if (child instanceof Form) {
                result.add((Form) child);
            } else if (child instanceof ViewGroup) {
                result.addAll(getFormControls((ViewGroup) child));
            } else {
            }
        }
        LogUtil.d("一共找到" + result.size() + "个表单控件");
        return result;
    }
}
